<!-- 前端/src/components/FilePreview.vue -->
<template>
    <div class="file-preview">
      <el-dialog
        v-model="dialogVisible"
        title="文件预览"
        width="80%"
        destroy-on-close
      >
        <div v-loading="loading" class="preview-content">
          <!-- PDF预览 -->
          <iframe
            v-if="previewUrl"
            :src="previewUrl"
            frameborder="0"
            width="100%"
            height="600px"
          ></iframe>
          
          <!-- 错误提示 -->
          <div v-if="error" class="error-message">
            {{ error }}
          </div>
        </div>
        
        <template #footer>
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="downloadFile">下载原文件</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref } from 'vue'
  import axios from 'axios'
  import { ElMessage } from 'element-plus'
  
  const props = defineProps({
    fileUrl: {
      type: String,
      required: true
    }
  })
  
  const dialogVisible = ref(false)
  const loading = ref(false)
  const previewUrl = ref('')
  const error = ref('')
  
  // 预览文件
  const previewFile = async () => {
    if (!props.fileUrl) {
      error.value = '文件地址不存在'
      return
    }
  
    loading.value = true
    error.value = ''
    
    try {
      const response = await axios({
        url: 'http://127.0.0.1:3007/api/info/preview/docx',
        method: 'POST',
        data: { fileUrl: props.fileUrl },
        responseType: 'blob'
      })
  
      // 创建 Blob URL
      const blob = new Blob([response.data], { type: 'application/pdf' })
      previewUrl.value = URL.createObjectURL(blob)
      
    } catch (err) {
      console.error('Preview error:', err)
      error.value = '文件预览失败，请稍后重试'
      ElMessage.error('预览失败')
    } finally {
      loading.value = false
    }
  }
  
  // 下载原文件
  const downloadFile = () => {
    if (!props.fileUrl) {
      ElMessage.warning('文件地址不存在')
      return
    }
    window.open(props.fileUrl, '_blank')
  }
  
  // 清理资源
  const cleanup = () => {
    if (previewUrl.value) {
      URL.revokeObjectURL(previewUrl.value)
      previewUrl.value = ''
    }
    error.value = ''
  }
  
  // 监听对话框关闭
  watch(dialogVisible, (newVal) => {
    if (!newVal) {
      cleanup()
    }
  })
  
  // 暴露方法给父组件
  defineExpose({
    showPreview: () => {
      dialogVisible.value = true
      previewFile()
    }
  })
  </script>
  
  <style scoped>
  .file-preview {
    width: 100%;
  }
  
  .preview-content {
    min-height: 600px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .error-message {
    color: #f56c6c;
    text-align: center;
  }
  </style>